<?php

namespace App\Http\Controllers;
use App\Models\EduCourseAttachment;
use Dcat\Admin\Traits\HasUploadedFile;
use Illuminate\Http\Request;

class AttachmentController extends Controller {
    use HasUploadedFile;

    /**
     * 文件上传接口 , 请求参数可以加一个driver指定使用哪个驱动
     *
     * @param String  $driver 要使用的文件驱动，默认public, 身份证等隐私信息是由local
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function upload(Request $request){
        try{
            $driver = $request->input("driver",env("FILESYSTEM_DRIVER", 'public'));

            $disk = $this->disk($driver);

            $file = $request->file("file");

            if (empty($file)) {
                return show_error("未检测到文件");
            }
            //$md5 = md5(md5_file($file) . time() . mt_rand(1000, 9999));//大文件取md5消耗性能
            $md5 = md5(unique_no());

            // 获取上传的字段名称
            $ext = strtolower($file->getClientOriginalExtension());
            $allows = config("filesystems.limit_ext.allows");
            $dir = "";
            foreach ($allows as $key => $val) {
                if (in_array($ext, $val)) {
                    $dir = $key;
                }
            }
            if ($dir === "" && config("filesystems.limit_ext.enable")) {
                return show_error("不允许上传的文件类型");
            }
            if ($dir === "") {
                $dir = "file";
            }

            $newName = date("Ym") . "/" . $md5 . "." . $file->getClientOriginalExtension();
            $result = $disk->putFileAs("uploads/" . $dir . "s", $file, $newName);
            if ($result) {
                $result=stripos($result,'/')===0?$result:'/'.$result;
                return show_success("上传成功",[
                    'driver'=>$driver,
                    'name'=>$file->getClientOriginalName(),
                    'path'=>$result,
                    'url'=> $disk->url($result) ,
                ]);
            }else{
                return show_error('上传失败');
            }
        }catch(\Exception $e){
            return show_error('上传失败',$e->getMessage());
        }
    }
}
